namespace Brjnk.GpxExplorer.UI.Controls
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using Brjnk.Common;
    using Brjnk.GpxExplorer.Localization;

    /// <summary>
    /// </summary>
    public class LocalizedTextBlock : TextBlock
    {
        static LocalizedTextBlock()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(LocalizedTextBlock), new FrameworkPropertyMetadata(typeof(LocalizedTextBlock)));
        }

        private WeakEventListener weakEventListener;

        public LocalizedTextBlock()
        {
            weakEventListener = new WeakEventListener(LocalizationChanged);
            PropertyChangedEventManager.AddListener(LocalizationManager.Instance, weakEventListener, "");
        }

        public string StringKey
        {
            get { return (string)GetValue(StringKeyProperty); }
            set { SetValue(StringKeyProperty, value); }
        }

        public static readonly DependencyProperty StringKeyProperty =
            DependencyProperty.Register("StringKey", typeof(string), typeof(LocalizedTextBlock), new UIPropertyMetadata(string.Empty, Changed));

        public object Argument
        {
            get { return (object)GetValue(ArgProperty); }
            set { SetValue(ArgProperty, value); }
        }

        public static readonly DependencyProperty ArgProperty =
            DependencyProperty.Register("Argument", typeof(object), typeof(LocalizedTextBlock), new UIPropertyMetadata(null, Changed));

        private static void Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var target = (LocalizedTextBlock)sender;
            target.RefreshText();
        }

        private bool LocalizationChanged(Type managerType, object sender, EventArgs e)
        {
            RefreshText();
            return true;
        }

        private void RefreshText()
        {
            var text = Brjnk.GpxExplorer.Localization.LocalizationManager.Instance.GetString(StringKey, Argument);
            SetCurrentValue(TextProperty, text);
        }
    }
}